package com.example.fzj.hazelcast.shiro;

/**
 * @Author fanzj
 * @Date 2021/8/15 4:59 下午
 * @Version 3.0
 * @Description
 */

import com.hazelcast.config.Config;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.map.IMap;
import org.apache.shiro.ShiroException;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.cache.MapCache;
import org.apache.shiro.util.Destroyable;
import org.apache.shiro.util.Initializable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Title: HazelcastCacheManager
 * Description: 重写，版本不合
 *
 * @author fanzj
 * @date 2021/8/15-5:00 下午
 */
public class HazelcastCacheManager implements CacheManager, Initializable, Destroyable {
    public static final Logger log = LoggerFactory.getLogger(org.apache.shiro.hazelcast.cache.HazelcastCacheManager.class);
    private boolean implicitlyCreated = false;
    private HazelcastInstance hazelcastInstance;
    private Config config;

    public HazelcastCacheManager() {
    }

    // 改写返回为IMap
    public <K, V> Cache<K, V> getCache(String name) throws CacheException {
        IMap<K, V> map = this.ensureHazelcastInstance().getMap(name);
        return new MapCache(name, map);
    }

    protected HazelcastInstance ensureHazelcastInstance() {
        if (this.hazelcastInstance == null) {
            this.hazelcastInstance = this.createHazelcastInstance();
            this.implicitlyCreated = true;
        }

        return this.hazelcastInstance;
    }

    public void init() throws ShiroException {
        this.ensureHazelcastInstance();
    }

    protected HazelcastInstance createHazelcastInstance() {
        return Hazelcast.newHazelcastInstance(this.config);
    }

    protected final boolean isImplicitlyCreated() {
        return this.implicitlyCreated;
    }

    public void destroy() throws Exception {
        if (this.implicitlyCreated) {
            try {
                this.hazelcastInstance.getLifecycleService().shutdown();
            } catch (Throwable var5) {
                if (log.isWarnEnabled()) {
                    log.warn("Unable to cleanly shutdown implicitly created HazelcastInstance.  Ignoring (shutting down)...", var5);
                }
            } finally {
                this.hazelcastInstance = null;
                this.implicitlyCreated = false;
            }
        }

    }

    public HazelcastInstance getHazelcastInstance() {
        return this.hazelcastInstance;
    }

    public void setHazelcastInstance(HazelcastInstance hazelcastInstance) {
        this.hazelcastInstance = hazelcastInstance;
    }

    public Config getConfig() {
        return this.config;
    }

    public void setConfig(Config config) {
        this.config = config;
    }
}
